import {post, dateFormat, getUserInfo} from './utils'
import $ from 'jquery'

// 跑马灯
$.fn.xfLamp = function (options) {
  let index = 2
  let div = $('<div></div>')
  let speed = options.speed || 0.5
  let height = this.height()
  let arr = options.data
  let item = $('<div style="height: ' + height + 'px" class="ellipsis"></div>')
  this.empty().append(div)
  for (var i = 0; i < arr.length; i++) {
    div.append(item.clone().attr('title', arr[i]).append(arr[i]))
  }
  div.prepend(item.clone().append(arr[arr.length - 1])).css('transform', 'translate(0, ' + -height + 'px)')
  var timer = setInterval(function () {
    if (!div.parent().length) {
      clearInterval(timer)
      return
    }
    div.css('transition', 'all ' + speed + 's ease')
    div.css('transform', 'translate(0, ' + -height * index + 'px)')
    if (index === arr.length) {
      /*
      div.off('transitionend').on('transitionend', function () {
        div.css({
          'transition': '',
          'transform': 'translate(0, 0)'
        }).off('transitionend')
      })
      index = 1
      */
      if (typeof options.end === 'function') {
        options.end()
      }
      clearInterval(timer)
    } else {
      index++
    }
  }, options.delay || 3000)
  return this
}

export default {
  install: (Vue) => {
    Vue.prototype.$post = post
    Vue.prototype.$dateFormat = dateFormat
    Vue.prototype.$userInfo = getUserInfo()
    // 自定义指令
    Vue.directive('img', {
      bind(el, binding, vnode) {
        $(el).attr('data-url', binding.value)
        $(el).css('cursor', 'pointer')
        el.addEventListener('click', e => {
          if (e && e.stopPropagation) {
            e.stopPropagation()
          } else {
            window.event.cancelBubble = true
          }
          const shade = $('<div class="preview-shade"></div>')
          const imgBox = $('<div class="preview-img"></div>')
          const rotate = $('<span class="el-icon-refresh preview-rotate"></span>')
          const image = $(`<img src="${el.dataset.url}">`)
          imgBox.append(image).append(rotate)
          $('body').append(shade).append(imgBox)
          imgBox.on('click', () => {
            shade.remove()
            imgBox.remove()
          })
          /*
          image.on('click', e => {
            if (e && e.stopPropagation) {
              e.stopPropagation()
            } else {
              window.event.cancelBubble = true
            }
          })
          */
          let currentRotate = 0
          rotate.on('click', e => {
            if (e && e.stopPropagation) {
              e.stopPropagation()
            } else {
              window.event.cancelBubble = true
            }
            currentRotate -= 90
            image.css('transform', `rotate(${currentRotate}deg)`)
          })
        }, false)
      },
      update(el, binding, vnode) {
        $(el).attr('data-url', binding.value)
      }
    })
  }
}
